package com.baomidou.springmvc.common.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Properties;

import org.apache.log4j.Logger;

/**
 * 根据路径读取配置文件，读取以后会缓存
 */
public class PropertiesUtils {

	public  static final  Logger log = Logger.getLogger(PropertiesUtils.class);

	private static Hashtable<String, Object> register = new Hashtable<String, Object>();

	private PropertiesUtils() {
		super();
	}
	
	@SuppressWarnings("resource")
	private static Properties getProperties(String fileName) {
		InputStream is = null;
		Properties p = null;
		try {
			p = (Properties) register.get(fileName);
		
			if (p == null) {
				try {
					is = new FileInputStream(fileName); 
				} catch (Exception e) {
					if (fileName.startsWith("/")){
						is = PropertiesUtils.class.getResourceAsStream(fileName);
					}else{
						is = PropertiesUtils.class.getResourceAsStream("/" + fileName);
					}
				}
				p = new Properties();
				p.load(is);
				register.put(fileName, p);
				is.close();
			}
		} catch (Exception e) {
			log.error(e,e);
		}
		return p;
	}

	
	public static String getString(String fileName, String strKey, String defaultValue) {
		Properties p = getProperties(fileName);
		try {
			return (String) p.getProperty(strKey,defaultValue);
		} catch (Exception e) {
			return defaultValue;
		}		
	}

}
